# itsdangerous 导入（加密解密） as 起别名
from itsdangerous import TimedJSONWebSignatureSerializer as Serializer
from django.conf import settings


def generate_openid_signature(openid):
    """数据加密"""
    serializer = Serializer(secret_key=settings.SECRET_KEY,expires_in=300)
    data = {"openid": openid}
    openid_sign = serializer.dumps(data).decode()
    return openid_sign
    # serializer = Serializer(secret_key=settings.SECRET_KEY, expires_in=600)
    # data = {'openid': openid}  # 把数据包装成字典
    # openid_sign = serializer.dumps(data)  # 加密后返回的数据是bytes类型
    # return openid_sign.decode()

def check_openid_sign(openid_sign):
    """数据解密"""
    serializer = Serializer(settings.SECRET_KEY, 300)
    try:
        data = serializer.loads(openid_sign)
    except BadData:  # 解密失败返回空
        return None
    else:
        return data.get("openid")

